<?php
namespace Frame\Libs;
use \Frame\Vendor\PDOWrapper;

//定义抽象的基础模型类
abstract class BaseModel
{
	//受保护的$pdo对象属性
	protected $pdo = NULL;
	//(私有的)受保护的静态的保存不同模型类对象的数组属性
	private static $arrModelObj = array();

	//构造方法
	public function __construct()
	{
		$this->pdo = new PDOWrapper();
	}
	//公共的静态的创建模型类对象的方法
	public static function getInstance()
	{
		//获取静态化方式调用的类名 
		$modelClassName = get_called_class();
		//get_called_class() 静态绑定类

		//判断当前模型类对象是否存在
		/*
			$arrModelObj['\Home\Model\StudentModel'] = 学生模型类对象 
		*/
		if(!isset(self::$arrModelObj[$modelClassName])){
			//如果当前模型类对象不存在,则创建并保存他
			self::$arrModelObj[$modelClassName] = new $modelClassName();
		}
		//返回当前模型类的对象
		return self::$arrModelObj[$modelClassName];
	}

    public function fetchAll()
    {
        $sql = "select * from {$this->table}";
        $result = $this->pdo->fetchAll($sql);
        return $result;
    }
    public function del($id)
    {
        $sql = "delete from {$this->table} where id=".$id;
        $result = $this->pdo->exec($sql);
        return $result;
    }
    public function insert($data)
    {
        //构建字符名列表和字段值列表字符串
        $fields = "";
        $values = "";
        foreach ($data as $key=>$val){
            $fields .= "$key,";
            $values .= "'$val',";
        }
        //去除字符串结果的逗号`
        $fields = rtrim($fields,",");
        $values = rtrim($values,",");
        $sql = "insert into {$this->table}($fields) values($values)";

        $result = $this->pdo->exec($sql);
        return $result;
    }
    //获取记录数
    public function rowCount($where="2>1")
    {
        $sql = "select * from {$this->table} where {$where}";
        $result = $this->pdo->rowCount($sql);
        return  $result;
    }
    //获取单条记录
    public function fetchOne($where="2>1")
    {
        $sql = "select * from {$this->table} WHERE {$where}";
        $result = $this->pdo->fetchOne($sql);
        return $result;
    }
    //修改记录
    public function edit($where="2>1",$id)
    {
        //测试参数传递是否正确
        //echo $last_login_ip."<br>".$last_login_time."<br>".$login_times;
        $sql = "update {$this->table} set {$where} where id='$id'";
        $result = $this->pdo->exec($sql);
        return $result;
    }
}